import { forwardRef, useImperativeHandle } from "react"
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';

import { useState } from "react"
import { useNavigate } from "react-router-dom";
import { cancelReserveSeatAPI, getUserReserveAPI } from "../../../apis/reserve";
import { getUserInfo } from "../../../utils/localStorage/userInfo";

const CancelDialog = forwardRef((props, ref) => {
    const navigate = useNavigate()

    const [open, setOpen] = useState(false);


    useImperativeHandle(ref, () => ({
        openDialog: () => {
            setOpen(true)
        },
        closeDialog: () => {
            setOpen(false)
        }
    }))

    const handleClickOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };

    // 取消预约
    const cancelReserve = async () => {
        let findReserveInfo = await getUserReserveAPI()
        let userInfo = getUserInfo()
        console.log('查询预约信息', findReserveInfo);
        let data = {
            id: findReserveInfo.data.id,
            seatId: findReserveInfo.data.seatId,
            roomsId: findReserveInfo.data.roomsId,
            studentId: parseInt(userInfo.id)
        }

        let cancelRes = await cancelReserveSeatAPI(data)
        console.log('取消预约', cancelRes);

        if (cancelRes.code == 1) {
            alert('取消预约成功')
            navigate('/classrooms',{replace:true})
        } else {
            alert('取消预约失败')
        }

    }

    return (
        <>
            <Dialog
                open={open}
                onClose={handleClose}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
            >
                <DialogTitle id="alert-dialog-title">
                    是否想要取消预约？
                </DialogTitle>
                <DialogContent>
                    <DialogContentText id="alert-dialog-description">
                        取消预约后你仍可以预约其他座位
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleClose}>再想想</Button>
                    <Button onClick={cancelReserve} autoFocus color="error" >
                        取消预约
                    </Button>
                </DialogActions>
            </Dialog>
        </>
    )
})

export default CancelDialog